from fastapi import APIRouter, Query

from tortoise.functions import Sum

from app.controllers.appointment.space import appointment_space_controller
from app.models import AppointmentDesigner, AppointmentList, OrdersList, CustomerUser, MiniAuditLog, MiniFav, OrdersCar, \
    BucklingDetail
from app.schemas.base import Success
from datetime import datetime

saas_space_router = APIRouter()
model_name = "门店"


@saas_space_router.get("/list", summary=f"查看{model_name}统计")
async def list_space(
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    total, spaces = await appointment_space_controller.do_list(page=1, page_size=20)
    data = []
    for space in spaces:
        space_status = '营业中' if True else '暂不营业'
        space_data = {
            'space_name': space['name'],
            'space_status': space_status,
            'date': await get_space_stats(space['id'], start_time, end_time)  # 获取门店详细数据
        }
        data.append(space_data)

    return Success(data=data)


async def get_space_stats(space_id, start_time, end_time):
    start_time_date = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S.%fZ")
    end_time_date = datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%S.%fZ")
    start_of_day = datetime.combine(start_time_date, datetime.min.time())  # 当天开始时间
    end_of_day = datetime.combine(end_time_date, datetime.max.time())  # 当天结束时间

    # 预约人数
    appointment_count = await AppointmentList.filter(
        space_id=space_id,
        time__range=(start_of_day, end_of_day)
    ).annotate(total=Sum('come_nums')).first().values("total")

    # 到店人数
    appointments = await AppointmentList.filter(
        space_id=space_id,
        time__range=(start_of_day, end_of_day)
    ).values('id', 'order_id', 'come_nums')

    total_come_nums = 0
    for appointment in appointments:
        order = await OrdersList.filter(
            id=appointment['order_id'],
            is_express=1
        ).first()

        # 第三步：统计符合条件的 come_nums 数量
        if order:
            total_come_nums += appointment['come_nums']

    # 取消人数
    cancelled_count = await AppointmentList.filter(
        space_id=space_id,
        time__range=(start_of_day, end_of_day),
        cancel_time__range=(start_of_day, end_of_day)
    ).annotate(total=Sum('come_nums')).first().values("total")

    # 业绩合计
    total_sales = await OrdersList.filter(
        address_id=space_id,
        created_at__range=(start_of_day, end_of_day),
        status=1,
    ).annotate(total=Sum('price')).first().values("total")

    # 门店合计
    store_sales = await OrdersList.filter(
        address_id=space_id,
        created_at__range=(start_of_day, end_of_day),
        status=1,
        type=1,
    ).annotate(total=Sum('price')).first().values("total")

    # 储值合计
    total_deposit = await OrdersList.filter(
        address_id=space_id,
        created_at__range=(start_of_day, end_of_day),
        status=1,
        type=3,
    ).annotate(total=Sum('price')).first().values("total")

    # 商品合计
    total_products = await OrdersList.filter(
        address_id=space_id,
        created_at__range=(start_of_day, end_of_day),
        status=1,
        type=2,
    ).annotate(total=Sum('price')).first().values("total")

    # 退款合计
    total_refunds = await OrdersList.filter(
        address_id=space_id,
        created_at__range=(start_of_day, end_of_day),
        status=4,
    ).annotate(total=Sum('price')).first().values("total")

    # 消耗合计
    total_consumption = await BucklingDetail.filter(
        created_at__range=(start_of_day, end_of_day),
    ).annotate(total=Sum('buckling_price')).first().values("total")

    # 当日注册
    daily_signups = await CustomerUser.filter(
        created_at__range=(start_of_day, end_of_day),
    ).count()

    # 当日浏览
    daily_views = await MiniAuditLog.filter(
        created_at__range=(start_of_day, end_of_day),
    ).count()

    # 当日邀请
    daily_invites = await CustomerUser.filter(
        created_at__range=(start_of_day, end_of_day),
        parent_id__isnull=False
    ).count()

    # 当日收藏
    daily_favorites = await MiniFav.filter(
        created_at__range=(start_of_day, end_of_day),
    ).count()

    # 当日加购
    daily_cart_adds = await OrdersCar.filter(
        created_at__range=(start_of_day, end_of_day),
    ).count()

    # 当日评论
    daily_comments = await OrdersList.filter(
        order_evaluations__isnull=False,
        updated_at__range=(start_of_day, end_of_day),
    ).count()

    # 构建数据
    stats = [
        {'name': "预约人数", 'value': int(appointment_count['total'] or 0), 'dw': "位"},
        {'name': "到店人数", 'value': int(total_come_nums), 'dw': "位"},
        {'name': "取消人数", 'value': int(cancelled_count['total'] or 0), 'dw': "位"},
        {'name': "业绩合计", 'value': int(total_sales['total'] or 0), 'dw': "元"},
        {'name': "门店合计", 'value': int(store_sales['total'] or 0), 'dw': "元"},
        {'name': "储值合计", 'value': int(total_deposit['total'] or 0), 'dw': "元"},
        {'name': "商品合计", 'value': int(total_products['total'] or 0), 'dw': "元"},
        {'name': "退款合计", 'value': int(total_refunds['total'] or 0), 'dw': "元"},
        {'name': "消耗合计", 'value': int(total_consumption['total'] or 0), 'dw': "元"},
        {'name': "当日注册", 'value': int(daily_signups), 'dw': "位"},
        {'name': "当日浏览", 'value': int(daily_views), 'dw': "位"},
        {'name': "当日邀请", 'value': int(daily_invites), 'dw': "位"},
        {'name': "当日收藏", 'value': int(daily_favorites), 'dw': "个"},
        {'name': "当日加购", 'value': int(daily_cart_adds), 'dw': "个"},
        {'name': "当日评论", 'value': int(daily_comments), 'dw': "个"},
    ]

    return stats
